// preload.js 中使用nodejs
const fs = require('fs')
const path = require('path');

/**
 * 
 * @param {*} dirPath 必传参数可以是文件夹可以是文件
 * @param {*} reservePath 保存path目录 path值与reservePath值一样就保存
 */
function delFile(dirPath, reservePath) {
    if (fs.existsSync(dirPath)) {
        if (fs.statSync(dirPath).isDirectory()) {
            let files = fs.readdirSync(dirPath);
            files.forEach((file, index) => {
                let currentPath = dirPath + "/" + file;
                if (fs.statSync(currentPath).isDirectory()) {
                    delFile(currentPath, reservePath);
                } else {
                    fs.unlinkSync(currentPath);
                }
            });
            if (dirPath != reservePath) {
                fs.rmdirSync(dirPath);
            }
        } else {
            fs.unlinkSync(dirPath);
        }
    }
}
window.readFolder = function (inputPath, extName, cb) {
    if (!fs.existsSync(inputPath)) {
        this.alert("输入文件夹不存在");
        return;
    }
    // const copyTempDir = outPutPath && outPutPath !== "" ? outPutPath : path.join(inputPath, "output");
    const readFiles = function () {
        // fs.mkdirSync(copyTempDir);
        let files = fs.readdirSync(inputPath);
        // const filePaths = [];
        const inputFilePaths = [];
        files.forEach((fileName) => {
            const ext = fileName.split(".")[1];
            if (extName === ext) {
                const oldPath = path.join(inputPath, fileName)
                // const destPath = path.join(copyTempDir, fileName);
                inputFilePaths.push(oldPath);
                // fs.copyFileSync(oldPath, destPath);
                // filePaths.push(destPath);
            }
        })
        cb(inputFilePaths);
    }
    readFiles();
    // if (fs.existsSync(copyTempDir)) {
    //     delFile(copyTempDir);
    //     readFiles();
    // } else {
    //     readFiles();
    // }
}
window.renameFileNames = function (oldFilePaths, outPutPath, extName, newFileNames) {
    if (!oldFilePaths || !oldFilePaths.length) {
        this.alert("旧的文件名列表为空")
        return;
    }
    if (!outPutPath) {
        this.alert("输出路径为空")
        return;
    }
    if (!newFileNames || !newFileNames.length) {
        this.alert("新的文件名列表为空")
        return;
    }
    if(!fs.existsSync(outPutPath)){
        fs.mkdirSync(outPutPath);
    }
    const newFilePaths = [];
    for (let i = 0; i < newFileNames.length; i++) {
        newFilePaths[i] = path.join(outPutPath, newFileNames[i] + `.${extName}`);
    }
    let oldFilePath;
    let newFilePath;
    for (let i = 0; i < oldFilePaths.length; i++) {
        oldFilePath = oldFilePaths[i];
        newFilePath = newFilePaths[i];
        if (oldFilePath && newFilePath) {
            fs.copyFileSync(oldFilePath, newFilePath);
        }
    }
}
